package utils

import (
	"context"
	"crypto/sha1"
	"crypto/tls"
	"encoding/hex"
	"io"
	"net/http"
	"os"
	"path"
	"wx-uniapp-go/third_party/cdslog"
)

var httpClient = &http.Client{
	Transport: &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	},
	Timeout: 0,
}

// SHA1 sha1
func SHA1(s string) string {
	o := sha1.New()
	o.Write([]byte(s))
	return hex.EncodeToString(o.Sum(nil))
}

// FileExist 是否存在
func FileExist(path string) bool {
	_, err := os.Lstat(path)
	return !os.IsNotExist(err)
}

// DownloadToLocalUseCache 下载
func DownloadToLocalUseCache(ctx context.Context, url string) (filePath, fileName string) {
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		cdslog.W(ctx).Error(err.Error())
		return
	}
	res, err := httpClient.Do(req)
	if err != nil {
		cdslog.W(ctx).Error(err.Error())
		return
	}
	defer res.Body.Close()

	fileName = path.Base(url)
	fileExt := path.Ext(fileName)
	fileSha1 := SHA1(url)
	filePath = "/tmp/" + fileSha1 + fileExt

	if FileExist(filePath) {
		return
	}

	f, err := os.Create(filePath)
	if err != nil {
		cdslog.W(ctx).Error(err.Error())
		return "", ""
	}
	defer f.Close()
	io.Copy(f, res.Body)
	return
}

// RemoveCacheFromURL 删除缓存文件
func RemoveCacheFromURL(url string) {
	fileSha1 := SHA1(url)
	fileName := path.Base(url)
	fileExt := path.Ext(fileName)
	filePath := "/tmp/" + fileSha1 + fileExt
	os.Remove(filePath)
}
